package com.hornet.manager.weixin.quartz;

import java.io.IOException;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.hornet.manager.weixin.constant.WeixinConstant;
import com.hornet.manager.weixin.json.AccessToken;
import com.hornet.manager.weixin.json.WeixinError;
import com.hornet.manager.weixin.util.WeixinContext;
import com.hornet.manager.weixin.util.WeixinHandler;

/**
 * 定时任务
 * 定时刷新微信AccessToken
 * @author Administrator
 *
 */
public class RefreshAccessTokenTask {
	
	private static Logger logger = LoggerFactory.getLogger(WeixinHandler.class);

	public void refreshAccessToken() {
		
		HttpGet get = null ;
		CloseableHttpClient client = null ;
		CloseableHttpResponse response = null ;
		
		try {
			client = HttpClients.createDefault() ;
			
			String url = WeixinConstant.ACCESS_TOKEN_URL ;
			url = url.replace("APPID", WeixinConstant.APPID);
			url = url.replace("APPSECRET", WeixinConstant.APPSECRET);
			
			get = new HttpGet(url) ;
			
			response = client.execute(get) ;
			int sc = response.getStatusLine().getStatusCode() ;
			if(sc >= 200 && sc< 300) {
				JSON json = (JSON) JSON.parse(EntityUtils.toString(response.getEntity())) ;
				try {
					AccessToken at = JSON.toJavaObject(json, AccessToken.class) ;
					WeixinContext.setAccessToken(at.getAccess_token());
					logger.info("定时刷新微信AccessToken成功：Access_Token[{}]", at.getAccess_token());
				} catch (Exception e) {
					WeixinError error = JSON.toJavaObject(json, WeixinError.class) ;
					logger.error("定时刷新微信AccessToken失败：{}", JSON.toJSON(error));
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null != get) {
				try {
					get.clone() ;
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
			}
			if(null != response) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null != client) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
